<?php

include ('config.php');

class Berita {

	private $connect;
	public $data;

	public function __construct() {
	
	}

	public function safe_query ($query = "") {
		if(empty($query)){
			return false;
		}
		$result = mysql_query($query);
		if ($result) {
		  return $result;
		} else {
		  $log = fopen("failquery.log", "ab");
		  $recDate = date("d-m-Y H:i");
		  $loginfo = "[$recDate] query failed: errorno=".mysql_errno().";error=".mysql_error().";\nquery=".$query."\n";
		  fwrite($log, $loginfo);
		  fclose($log);
		  return FALSE;
		}
	}
	
	public function lihat ($table,$id,$order) {
		if ($id == "") {
			$query = "SELECT * FROM `".$table."` ORDER BY `".$order."`";
		} elseif ($order == "") {
			$query = "SELECT * FROM `".$table."` WHERE `idberita` = '".$id."'";
		}
		
		$result = $this->safe_query($query);
		if(($result) && (mysql_num_rows($result) > 0)) {
			$data = array();
			while($row = mysql_fetch_assoc($result))
			$data[] = $row;
			return $data;
		} else {
			return FALSE;
		}
	}
	
	public function lihat_5berita ($table,$order) {
		$query = "SELECT * FROM `".$table."` ORDER BY `".$order."` DESC LIMIT 0,5";
		$result = $this->safe_query($query);
		if(($result) && (mysql_num_rows($result) > 0)) {
			$data = array();
			while($row = mysql_fetch_assoc($result))
			$data[] = $row;
			return $data;
		} else {
			return FALSE;
		}
	}
	
	public function tambah ($table,$data) {
		$fields = array();
		$values = array();
	    foreach($data as $key=>$value) {
			$fields[] ="`$key`";
			$values[] ="'$value'";
		}
	    $query = "INSERT INTO `".$table."` (".implode(',',$fields).") VALUES (".implode(',',$values).")";
		$result = $this->safe_query($query);
		if ($result && (mysql_affected_rows()>0))
			return TRUE;
		else
			return FALSE;
	}
	
	public function hapus ($table,$id) {
	    $query = "DELETE FROM `".$table."` WHERE idberita = '".$id."'";	  
		$result = $this->safe_query($query);
		if ($result && (mysql_affected_rows()>0))
			return TRUE;
		else
			return FALSE;
	}
	
	public function ubah ($id, $table, $field) {
		$fields = array();
		foreach($field as $key=>$value) { 
			$fields[] = $key."="."'".$value."'";
		}							
	    $query = "UPDATE `".$table."` SET ".implode(',',$fields)." where id="."'".$id."'";	  
		$result = $this->safe_query($query);
		if ($result && (mysql_affected_rows()>0))
			return TRUE;
		else
			return FALSE;
	}
}
